import { Controller, Post, Req } from '@nestjs/common';
import { ChildProcessWithoutNullStreams, spawn } from 'child_process';

@Controller()
export class AppController {

    @Post('git')
    async git(@Req() req) {
        const password: string = '6688';
        const currentPath: string = '/www/wwwroot/km.cdn001-baidu.com';
        if (req.headers['x-gitee-token'] === password) {
            try {
                this.cmd('sh', ['/www/wwwroot/km.cdn001-baidu.com/node/public/cmd/cmd.sh'], currentPath).then(res => {
                    console.log(res);
                })
                return { msg: 'success' }
            } catch (error) {
                return error
            }
        } else {
            return { msg: '???' }
        }
    }

    cmd(cmd: string, args: string[], currentPath: string) {
        return new Promise((resolve) => {
            console.log('执行脚本');

            const child: ChildProcessWithoutNullStreams = spawn(cmd, args, {
                cwd: currentPath,
            })
            var response: string = ''
            child.stdout.on('data', function (buffer: Buffer) {
                response += buffer.toString();
            })
            child.stdout.on('end', function () {
                console.log('脚本执行完成');
                resolve(response)
            })
        })
    }
}
